#!/usr/bin/python
# coding:utf-8
import argparse
import os, sys


def get_dict(file):
    """ 将文件内容转化为字典 """
    file_dict = {}
    with open(file) as f:
        for line in f.readlines():
            if line.startswith("#") or line.startswith(";") or len(line.strip()) == 0:
                continue
            elif line.strip().startswith("[") and line.strip().endswith("]"):
                key = line.strip().lstrip("[").rstrip("]")
                file_dict[key] = []
            else:
                file_dict[key].append(line.rstrip("\n"))
    return file_dict


def cmp_list(list1, list2):
    """ 列表对比 """
    tmp1 = []
    tmp2 = []
    if cmp(list1, list2) != 0:
        for a in list1:
            if a not in list2:
                tmp1.append(a)
        for b in list2:
            if b not in list1:
                tmp2.append(b)
    return {'lest': tmp1, 'right': tmp2}


def cmp_dict(dict1, dict2):
    """ 字典对比 """
    diff_dict = {}
    if cmp(dict1, dict2) == 0:
        print('两个文件的内容相同!')
        return {}

    for key in dict1.keys():
        if key in dict2.keys():
            list1 = dict1[key]
            list2 = dict2[key]
            result = cmp_list(list1, list2)
            diff_dict[key] = result
        else:
            diff_dict[key] = {'left': dict1[key]}
    for key in dict2.keys():
        if key not in dict1.keys():
            diff_dict[key] = {'right': dict2[key]}
    return diff_dict


def printer(dict):
    """ 打印机 """
    for key in dict.keys():
        print('\n[%s]' % key)
        for item in dict[key]:
            print("---%s" % item)
            for str in dict[key][item]:
                print(str)


def main(args):
    file1 = args.first_file if args.first_file.startswith('/') else os.path.abspath(args.first_file)
    file2 = args.second_file if args.second_file.startswith('/') else os.path.abspath(args.second_file)

    if not os.path.isfile(file1):
        print('%s is not a file !' % file1)
        exit()
    if not os.path.isfile(file2):
        print('%s is not a file !' % file1)
        exit()

    result = cmp_dict(get_dict(file1), get_dict(file2))
    printer(result)


if __name__ == "__main__":
    '''  '''
    base_dir = os.getcwd()
    parse = argparse.ArgumentParser()
    parse.add_argument('first_file', type=str, help='the first file')
    parse.add_argument('second_file', type=str, help='the second file')
    args = parse.parse_args()
    main(args)
